#!/usr/bin/env python
# encoding: utf-8

print "cwmail"

# built-in stuff
import unittest
import sys
sys.path.append("../")
# home made stuff
from scriptgoodies import getTestingEnvironment
# stuff to test
from cwmail import *

class CwMailTest(unittest.TestCase):
	
	def testRun(self):
		# initialize environment
		env = getTestingEnvironment("cwmail.json")
		env["meta"]["name"] = u"cwMail"
		env["meta"]["richSuffix"] = u""
		env["prefs"]["cwMail_defaultSignature"] = u""
		# the script should generate an empty form when called with an empty text
		template = codecs.open("template.txt","r","utf8").read()
		expectedForm = "cwMail(=\n%s)" % re.sub(r"%\(\S+?\)s","",template)
		env["context"]["selection"] = ""
		form = dict(main(env))["replace"]
		self.assertEqual(form,expectedForm)
		# the script should generate a pre-filled form when called with an empty text and non empty default fields
		env["prefs"]["cwMail_user"] = u'testchewingword@yahoo.fr' # for an alternative address, swap "test" and "chewingword".
		env["prefs"]["cwMail_passwordMasked"] = u''
		env["prefs"]["cwMail_defaultToField"] = u'chewingwordtest@yopmail.com'
		env["prefs"]["cwMail_defaultCcField"] = u'chewingwordtestcc1@yopmail.com, chewingwordtestcc2@yopmail.com'
		env["prefs"]["cwMail_defaultBccField"] = u'chewingwordtestbcc@yopmail.com'
		env["prefs"]["cwMail_defaultSubjectField"] = u'test codé en UTF-8'
		expectedForm = "cwMail(=\n%s)" % template % env["prefs"]
		form = dict(main(env))["replace"]
		self.assertEqual(form,expectedForm)
		# the script should extract the value of the various fields
		env["prefs"]["cwMail_body"] = u'Un échantillon de texte codé en UTF-8.\n加上几个汉字。'
		env["context"]["selection"] = template % env["prefs"]
		d = getFilledForm(env)
		self.assertEqual(d['From'],env["prefs"]["user"])
		self.assertEqual(d['Password'],env["prefs"]["cwMail_passwordMasked"])
		self.assertEqual(d['To'],env["prefs"]["cwMail_defaultToField"])
		self.assertEqual(d['Cc'],env["prefs"]["cwMail_defaultCcField"])
		self.assertEqual(d['Bcc'],env["prefs"]["cwMail_defaultBccField"])
		self.assertEqual(d['Subject'],env["prefs"]["cwMail_defaultSubjectField"])
		self.assertEqual(d['Body'],env["prefs"]["cwMail_body"])
		# the script should actually send the mail
		env["prefs"]["archiveDirectory"] = u"."
		env["static"]["cw_archiveTimeFormat"] = u"%Hh%M"
		env["prefs"]["archiveUnsaved"] = "yes"
		# fail to send the mail
		self.assertRaises(smtplib.SMTPServerDisconnected,sendMail,d,env)
		# send the mail
		env["prefs"]["cwMail_smtp"] = u"smtp.mail.yahoo.fr"
		env["prefs"]["cwMail_port"] = u"465"
		env["prefs"]["cwMail_ssl"] = u"x"
		env["prefs"]["cwMail_passwordMasked"] = u"fant7yoz2d"
		sendMail(d,env)
		print("Success: please manually check your yopmail.com mailboxes.")
		mayArchiveMail(d,env)
		print("Success: please manually check the archive in the current directory.")


if __name__ == '__main__':
	unittest.main()


